package com.lpb.spring.lpbspring.getway.util;

import org.apache.commons.lang3.RandomStringUtils;

import java.util.Random;

/**
 * Created by wisdom on 2017/5/1.
 */
public final class IdUtils {
    private static final String FLAG = "c";
    private static final int TOTAL = 32;
    private static final int SIGN_START = 10;
    private static final int SIGN_END = 12;
    private static final String CHARS = "abcdef0123456789";
    private static final int CONFUSION = 7;
    private static final int RADIX = 9;
    private static final int SUPPLEMENT = 1;
    private static final int LEN = 2;
    private static final int MAX_RADIX = 16;
    private static final int MIN_RADIX = 10;

    private IdUtils() {
    }

    public static String getId(Long id) {
        if (id == null) {
            return null;
        }

        int radix = getRadix();
        String idRadix = Long.toString(id, radix);
        int len = idRadix.length();
        int sign = TOTAL - len - SUPPLEMENT - LEN - LEN;

        return FLAG + Integer.toString(radix, RADIX) + RandomStringUtils.random(CONFUSION, CHARS) + Integer.toString(sign, RADIX) + idRadix + RandomStringUtils.random(sign - CONFUSION, CHARS);
    }

    public static String getInvariableId(Long id) {
        if (id == null) {
            return null;
        }
        int radix = 13;
        String idStr = Md5.getMD5(String.valueOf(id));
        String idRadix = Long.toString(id, radix);
        int len = idRadix.length();
        int sign = TOTAL - len - SUPPLEMENT - LEN - LEN;
        StringBuilder aid = new StringBuilder(FLAG);
        aid.append(Integer.toString(radix, RADIX));
        aid.append(idStr, aid.length(), aid.length() + CONFUSION);
        aid.append(Integer.toString(sign, RADIX));
        aid.append(idRadix);
        aid.append(idStr.substring(aid.length()));
        return aid.toString();
    }

    protected static int getRadix() {
        return new Random().nextInt(MAX_RADIX) % (MAX_RADIX - MIN_RADIX + SUPPLEMENT) + MIN_RADIX;
    }

    public static Long getId(String id) {
        if (id == null || id.length() != TOTAL || !id.startsWith(FLAG)) {
            return null;
        }
        int sign = Integer.valueOf(id.substring(SIGN_START, SIGN_END), RADIX);
        int radix = Integer.valueOf(id.substring(FLAG.length(), FLAG.length() + LEN), RADIX);
        if (sign > 27 || radix > MAX_RADIX || radix < 10) {
            return null;
        }
        return Long.valueOf(id.substring(SIGN_END, TOTAL - sign + CONFUSION), radix);
    }

    public static boolean isId(String id) {
        try {
            return id != null && id.length() == TOTAL && id.startsWith(FLAG) && getId(id) > 0;
        } catch (Exception e) {
            return false;
        }
    }

}
